<template>
  <div class="data-list flex-auto overflow-y">
    <div class="page-container-inner full-height full-width no-scroll-x no-scroll-y flex-column">
      <!-- 查询条件区域 -->
      <div v-if="dataConfig.search" class="search-area flex-row flex-row-between">
        <template v-if="dataConfig.search.conditions && dataConfig.search.conditions.length">
          <el-form class="flex-auto flex-row column-center flex-wrap" size="medium" ref="searchForm" :model="searchForm"
            :label-width="dataConfig.search.labelWidth || '100px'">
            <el-form-item v-for="(item, index) in dataConfig.search.conditions" :key="index" :prop="item.prop"
              :label="`${item.label}：`" :label-width="item.labelWidth">
              <template v-if="item.type === 'input'">
                <el-input v-model="searchForm[item.prop]" :placeholder="`请输入${item.label}`"
                  :style="item.inputWidth ? `width: ${item.inputWidth};` : 'width: 200px;'" clearable
                  @keyup.enter.native="search"></el-input>
              </template>
              <template v-if="item.type === 'select'">
                <el-select v-model="searchForm[item.prop]" :placeholder="`请选择${item.label}`" clearable>
                  <el-option v-for="(option, oIndex) in item.options" :key="oIndex" :label="option.name"
                    :value="option.value">
                  </el-option>
                </el-select>
              </template>
            </el-form-item>
            <el-form-item label-width="20px">
              <div class="flex-row search-button">
                <app-button :loading="dataConfig.search && dataConfig.search.loading" @click="handleSearch">查询</app-button>
                <app-button :loading="dataConfig.search && dataConfig.search.loading" @click="research"
                  plain>重置</app-button>
              </div>
            </el-form-item>
          </el-form>
        </template>
        <!-- 如果没有查询条件，则放置一个空div，用于占位以便把其他操作按钮撑开到右侧 -->
        <template v-else>
          <div class="flex-auto"></div>
        </template>
        <template v-if="dataConfig.search.topOperates && dataConfig.search.topOperates.length">
          <app-button v-for="(item, index) in dataConfig.search.topOperates" :key="index" @click="item.callback"
            :link="item.type === 'link'" :underline="item.underline">{{ item.label }}</app-button>
        </template>
      </div>
      <!-- 列表展示区域 -->
      <div class="table-area flex-auto no-scroll-x overflow-y">
        <el-table size="medium" border :data="dataList" :stripe="true"
          v-loading="dataConfig.search && dataConfig.search.loading" height="100%" style="width: 100%"
          @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
          <el-table-column v-if="dataConfig.table && dataConfig.table.config && dataConfig.table.config.select"
            type="selection" width="60">
          </el-table-column>
          <!-- <el-table-column v-if="dataConfig.table && dataConfig.table.config && dataConfig.table.config.index"
            type="index" :label="dataConfig.table.config.indexLabel || '序号'" width="60">
          </el-table-column> -->
          <el-table-column type="index" label="序号" width="60">
          </el-table-column>
          <template v-if="dataConfig.table && dataConfig.table.columns && dataConfig.table.columns.length">
            <template v-for="(item, index) in dataConfig.table.columns">
              <!-- <el-table-column v-if="item.type === 'text'" :key="index" :prop="item.prop" :label="item.label"
                :fixed="item.fixed" :width="item.width" :align="item.align" :show-overflow-tooltip="item.tooltip"> -->
              <el-table-column v-if="item.type === 'text'" :key="index" :prop="item.prop" :label="item.label"
                :width="item.width" :align="item.align" :show-overflow-tooltip="item.tooltip">
                <template slot-scope="scope">
                  <div class="flex-row column-center" :style="{}">
                    <span :style="item.tooltip ? 'text-overflow: ellipsis; overflow: hidden;' : ''">
                      {{ (typeof item.callback === 'function' && item.callback(scope.row))
                        || (scope.row[item.prop] === '' || scope.row[item.prop] === null || scope.row[item.prop] ===
                          undefined
                          ? '-' : (scope.row[item.prop] + '').trim()) }}</span>
                    <template v-if="item.button && item.button.length">
                      <app-button style="margin-left: 5px;" link
                        @click="typeof item.event === 'function' && item.event(scope.row)">{{ item.button
                        }}</app-button>
                    </template>
                    <template v-if="item.hasProgress && scope.row.hasProgress">
                      <div style="width: 100px; margin-left: 5px;">
                        <el-progress :text-inside="true" status="success" define-back-color="#cccccc" text-color="#ffffff"
                          :stroke-width="14" :percentage="scope.row.progressValue"></el-progress>
                      </div>
                    </template>
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column v-if="item.type === 'operates' && item.operates && item.operates.length" :key="index"
                :prop="item.prop" :label="item.label" :fixed="item.fixed" :width="item.width"> -->
              <el-table-column v-if="item.type === 'operates' && item.operates && item.operates.length" :key="index"
                :prop="item.prop" :label="item.label" :width="item.width">
                <template slot-scope="scope">
                  <div class="flex-row column-center">
                    <template v-for="(oItem, oIndex) in item.operates">
                      <app-button :key="oIndex" :link="oItem.type === 'link'"
                        v-if="(typeof oItem.show === 'function' ? oItem.show(scope.row) : true)"
                        @click="oItem.callback(scope.row)">{{ (typeof oItem.label === 'function' &&
                          oItem.label(scope.row))
                          || oItem.label }}</app-button>
                    </template>
                  </div>
                </template>
              </el-table-column>
            </template>
          </template>
        </el-table>
      </div>
      <!-- 分页展示区域，靠左展示：flex-left；靠右展示：flex-right；居中展示：flex-center -->
      <div class="pagination-area flex-row flex-left">
        <el-pagination v-if="refreshPagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pageInfo.pageNum" :page-sizes="$utils.getSystemConfig().PAGE_SIZES"
          :page-size="pageInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import AppButton from '@/components/common/app-button/app-button.vue';
export default {
  name: 'DataList',
  components: { AppButton },
  props: {
    dataConfig: {
      type: Object,
      default() {
        return {}
      },
    },
    tableData: {
      type: Object,
      default() {
        return {}
      },
    },
    cacheParam: {
      type: Boolean,
      default() {
        return false
      },
    },
  },
  data() {
    return {
      searchForm: { ...(this.dataConfig.search && this.dataConfig.search.form || {}) },
      pageInfo: {
        pageSize: this.$utils.getSystemConfig().DEFAULT_PAGE_SIZE,
        pageNum: this.$utils.getSystemConfig().DEFAULT_PAGE_NUM,
      },
      // 当页码发生变化时，强制刷新分页组件以刷新组件中的信息（目前分页组件存在BUG无法自动更新数据）
      refreshPagination: true,
    };
  },
  computed: {
    dataList() {
      return [...(this.tableData && this.tableData.data || [])];
    },
  },
  beforeDestroy() { },
  created() {
  },
  methods: {
    tableRowClassName(item) {
      return item.row.dataWarning ? 'warning-row' : '';
    },
    handleSizeChange(e) {
      this.pageInfo.pageNum = 1;
      this.pageInfo.pageSize = e;
      // 每页展示条数发生变化时，使用原来的查询条件
      this.searchForm = JSON.parse(this.oldSearchFormStr);
      this.searchData(this.pageInfo, this.searchForm);
    },
    handleCurrentChange(e) {
      this.pageInfo.pageNum = e;
      // 翻页时，使用原来的查询条件
      this.searchForm = JSON.parse(this.oldSearchFormStr);
      this.searchData(this.pageInfo, this.searchForm);
    },
    handleSelectionChange(val) {
      if (this.dataConfig.table && this.dataConfig.table.config && this.dataConfig.table.config.select) {
        if (typeof this.dataConfig.table.config.selectCallback === 'function') {
          this.dataConfig.table.config.selectCallback(val);
        }
      }
    },
    research() {
      this.$refs['searchForm'].resetFields();
      this.pageInfo.pageSize = this.$utils.getSystemConfig().DEFAULT_PAGE_SIZE;
      this.pageInfo.pageNum = this.$utils.getSystemConfig().DEFAULT_PAGE_NUM;
      this.searchData(this.pageInfo, this.searchForm);
    },
    handleSearch() {
      // 如果查询条件发生改变，则将页码置为1
      if (this.oldSearchFormStr !== JSON.stringify(this.searchForm)) {
        this.pageInfo.pageNum = 1;
      }
      this.searchData(this.pageInfo, this.searchForm);
    },
    search() {
      // 如果设置了需要记录当前页面查询参数，当用户查询时，使用页面缓存的参数进行查询
      if (this.cacheParam) {
        this.$log.debug('已缓存的查询条件为：', this.$route.query.searchForm, '，分页信息为：', this.$route.query.pageInfo);
        const pageInfoStr = this.$utils.decodeBase64(this.$route.query.pageInfo);
        const searchFormStr = this.$utils.decodeBase64(this.$route.query.searchForm);
        if (pageInfoStr && pageInfoStr.length && searchFormStr && searchFormStr.length) {
          this.pageInfo = { ...JSON.parse(pageInfoStr) };
          this.searchForm = { ...JSON.parse(searchFormStr) };
        }
        this.refreshPagination = false;
        this.$nextTick(() => {
          this.refreshPagination = true;
        });
      }
      this.searchData(this.pageInfo, this.searchForm);
    },
    searchData(pageInfo, searchForm) {
      // 如果设置了需要记录当前页面查询参数，则将查询参数保存至浏览器地址中，当用户返回时，还可以继续使用该查询参数进行查询
      // 将当前页面所有参数封装至页面URL中 BEGIN
      if (this.cacheParam) {
        const pageInfoStr = this.$utils.encodeBase64(JSON.stringify(pageInfo));
        const searchFormStr = this.$utils.encodeBase64(JSON.stringify(searchForm));
        const currentParams = {
          ...this.$route.query,
          pageInfo: pageInfoStr,
          searchForm: searchFormStr
        };
        this.$log.debug('待缓存的查询条件为：', searchFormStr, '，分页信息为：', pageInfoStr);
        let urlParams = [];
        for (const key in currentParams) {
          urlParams.push(`${key}=${currentParams[key]}`);
        }
        let newUrl = window.location.href.split('?')[0] + '?' + urlParams.join('&');
        history.replaceState(null, null, newUrl);
      }
      // 将当前页面所有参数封装至页面URL中 END
      this.oldSearchFormStr = JSON.stringify(this.searchForm);
      if (this.dataConfig.search && typeof this.dataConfig.search.searchCB === 'function') {
        this.dataConfig.search.searchCB(pageInfo, searchForm);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.data-list {}
</style>
